package com.q.tqb.activity.mine;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonElement;
import com.q.tqb.R;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.luban.Luban;
import com.q.tqb.luban.OnCompressListener;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IRawResponse;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.util.oss.OssCallback;
import com.q.tqb.util.oss.OssService;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MineAddBusinessActivity extends BaseActivity {


    @BindView(R.id.et_business_name)
    EditText etBusinessName;
    @BindView(R.id.et_business_tel)
    EditText etBusinessTel;
    @BindView(R.id.et_business_address)
    EditText etBusinessAddress;
    @BindView(R.id.iv_card_front)
    ImageView ivCardFront;
    @BindView(R.id.iv_card_behind)
    ImageView ivCardBehind;
    @BindView(R.id.iv_business_licence)
    ImageView ivBusinessLicence;
    @BindView(R.id.iv_businessman)
    ImageView ivBusinessman;
    @BindView(R.id.iv_store)
    ImageView ivStore;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;

    private int imageType;
    private static final int TAKE_PHOTO = 33;
    private static final int SELECT_PHOTO = 34;

    private boolean isImage1;
    private boolean isImage2;
    private boolean isImage3;
    private boolean isImage4;
    private boolean isImage5;

    private int uid;
    private int imageAmount;
    private String[] upPointNames;


    @Override
    public int getLayoutId() {
        return R.layout.activity_mine_add_business;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        setTitle(getString(R.string.mine_add_store));
        uid = (int) SPUtil.get(this, "uid", 0);
        upPointNames = new String[5];

    }


    @OnClick({R.id.iv_back, R.id.iv_card_front, R.id.iv_card_behind, R.id.iv_business_licence, R.id.iv_businessman, R.id.iv_store, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_card_front:
                imageType = 1;
                showDialog();
                break;
            case R.id.iv_card_behind:
                imageType = 2;
                showDialog();
                break;
            case R.id.iv_business_licence:
                imageType = 3;
                showDialog();
                break;
            case R.id.iv_businessman:
                imageType = 4;
                showDialog();
                break;
            case R.id.iv_store:
                imageType = 5;
                showDialog();
                break;
            case R.id.tv_submit:
                checkBusiness();
                break;
            default:
                break;
        }
    }

    private void checkBusiness() {
        String storeName = etBusinessName.getText().toString();
        String storeTel = etBusinessTel.getText().toString();
        String storeAddress = etBusinessAddress.getText().toString();
        if (TextUtils.isEmpty(storeName) && TextUtils.isEmpty(storeTel) && TextUtils.isEmpty(storeAddress)) {
            showToast("信息不完整");
            return;
        }
        if (!(isImage1 && isImage2 && isImage3 && isImage4 && isImage5)) {
            showToast("请上传完需要的图片");
            return;
        }
        mProgressDialog.show();
        for (int i = 1; i < 6; i++) {
            String path = getExternalCacheDir() + "buss_image_" + i + ".jpg";
            String upPointName = "image/" + uid + "_" + System.currentTimeMillis() + ".JPEG";
            upPointNames[i - 1] = AppConst.OSS_URL + upPointName;
            OssService.asyncPutFile(upPointName, path, new OssCallback(new Handler(), new IRawResponse() {
                @Override
                public void onSuccess(String response) {
                    imageAmount++;
                    if (imageAmount == 5) {
                        upBusiness();
                    }
                }

                @Override
                public void onFailure(String errorMsg) {
                    mProgressDialog.dismiss();
                    showToast("请检查您的网络");
                    imageAmount = 0;
                    LogUtil.i(errorMsg);
                }
            }));
        }
    }

    private void upBusiness() {
        String storeName = etBusinessName.getText().toString();
        String storeTel = etBusinessTel.getText().toString();
        String storeAddress = etBusinessAddress.getText().toString();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        map.put("merchant_name", storeName);
        map.put("merchant_phone", storeTel);
        map.put("merchant_address", storeAddress);
        map.put("idcard1", upPointNames[0]);
        map.put("idcard2", upPointNames[1]);
        map.put("business_license", upPointNames[2]);
        map.put("legal_and_idcard", upPointNames[3]);
        map.put("enterprise_pic", upPointNames[4]);
        OkHttpUtil.getInstance().post(MineAddBusinessActivity.this, AppConst.URL_APPLY_MERCHANT, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                LogUtil.i(element.toString());
                showToast("申请商户成功，等待审核！");
                SPUtil.put(MineAddBusinessActivity.this, "isMerchant", 1);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                mProgressDialog.dismiss();
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });


    }

    private void showDialog() {
        final String[] items = {"相册选择", "相机拍照"};
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MineAddBusinessActivity.this);
        singleChoiceDialog.setTitle("选择方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    selectPhoto();
                } else {
                    takePhoto();
                }
                dialog.dismiss();
            }
        });

        singleChoiceDialog.show();
    }

    private void selectPhoto() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, SELECT_PHOTO);
    }

    private void takePhoto() {

        File file = new File(getImagePath());
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Uri imageUri = Uri.fromFile(file);
        //启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }


    private String getImagePath() {
        String path = null;
        if (imageType == 1) {
            path = getExternalCacheDir() + "buss_image_1.jpg";
        } else if (imageType == 2) {
            path = getExternalCacheDir() + "buss_image_2.jpg";
        } else if (imageType == 3) {
            path = getExternalCacheDir() + "buss_image_3.jpg";
        } else if (imageType == 4) {
            path = getExternalCacheDir() + "buss_image_4.jpg";
        } else if (imageType == 5) {
            path = getExternalCacheDir() + "buss_image_5.jpg";
        }
        return path;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PHOTO && resultCode == RESULT_OK) {
            Luban.with(this)
                    .load(getImagePath())
                    .setTargetDir(getImagePath())
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            showBitmap(file.getAbsolutePath());
                        }

                        @Override
                        public void onError(Throwable e) {
                            showToast("图片压缩失败，请重新选择");
                        }
                    }).launch();    //启动压缩
        }
        if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
            try {
                Uri selectedImage = data.getData();
                assert selectedImage != null;
                LogUtil.i(selectedImage.toString());

                String picturePath = null;
                String[] projection = {MediaStore.Images.Media.DATA};
                assert selectedImage != null;
                Cursor cursor = this.getContentResolver().query(selectedImage, projection, null, null, null);
                assert cursor != null;
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                picturePath = cursor.getString(columnIndex);
                cursor.close();
                if (picturePath != null) {
                    Luban.with(this)
                            .load(picturePath)
                            .ignoreBy(100)
                            .setTargetDir(getImagePath())
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(File file) {
                                    showBitmap(file.getAbsolutePath());
                                }

                                @Override
                                public void onError(Throwable e) {
                                    showToast("图片压缩失败，请重新选择");
                                }
                            }).launch();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void showBitmap(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (path.contains("image_1.jpg")) {
            isImage1 = true;
            ivCardFront.setImageBitmap(bitmap);
        } else if (path.contains("image_2.jpg")) {
            isImage2 = true;
            ivCardBehind.setImageBitmap(bitmap);
        } else if (path.contains("image_3.jpg")) {
            isImage3 = true;
            ivBusinessLicence.setImageBitmap(bitmap);
        } else if (path.contains("image_4.jpg")) {
            isImage4 = true;
            ivBusinessman.setImageBitmap(bitmap);
        } else if (path.contains("image_5.jpg")) {
            isImage5 = true;
            ivStore.setImageBitmap(bitmap);
        }
    }


}
